package com.cookor.poi.modules.phy.mobile;

import com.cookor.poi.common.utils.ResultUtil;
import com.cookor.poi.modules.phy.entity.TWeixinUser;
import com.cookor.poi.modules.phy.service.TWeixinUserService;
import com.cookor.poi.modules.weixin.account.Account;
import com.cookor.poi.modules.weixin.account.PlatformAccount;
import com.cookor.poi.modules.weixin.entity.TWeixinConfig;
import com.cookor.poi.modules.weixin.service.TWeixinConfigService;
import com.xiaoleilu.hutool.json.JSONObject;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.view.RedirectView;

@Controller
@RequestMapping({"/api/phy/wx"})
@ResponseBody
public class ApiWxController extends ApiBaseController {
  @Autowired
  private TWeixinConfigService tWeixinConfigService;
  
  @Autowired
  private TWeixinUserService tWeixinUserService;
  
  @RequestMapping({"/oauth"})
  public ResultUtil Oauth(HttpServletRequest request) {
    ResultUtil result = getResult();
    try {
      String code = request.getParameter("code");
      Integer tenantId = getTenantId(request);
      if (StringUtils.isBlank(code)) {
        System.out.println("通信错误，请在微信中重新发起请求");
        return null;
      } 
      TWeixinConfig config = this.tWeixinConfigService.findByTenantId(tenantId);
      Account account = Account.factory(config.getId());
      JSONObject jo = account.getOauthInfo(code);
      String openid = jo.getStr("openid");
      String access_token = jo.getStr("access_token");
      if (StringUtils.isBlank(openid) || openid.equals("null") || openid == null)
        throw new Exception("openid异常"); 
      System.out.println(openid);
      TWeixinUser user = this.tWeixinUserService.getByOpenId(openid);
      if (user == null) {
        jo = Account.getOauthUserInfo(access_token, openid);
        user = (TWeixinUser)jo.toBean(TWeixinUser.class);
        user.setUniacid(tenantId);
        this.tWeixinUserService.save(user);
      } 
      result.putParams("openid", openid);
      result.putParams("user", user);
    } catch (Exception e) {
      result.setCode(ResultUtil.ERROR_CODE);
      result.setError(e.getMessage());
      this.logger.error("ApiWxController Oauth error!", e);
    } 
    return result;
  }
  
  @RequestMapping({"/open/getCode"})
  public ModelAndView openGetCode(HttpServletRequest request) {
    String code = request.getParameter("code");
    String url = request.getParameter("url");
    if (StringUtils.isBlank(code) || StringUtils.isBlank(url))
      this.logger.error("openGetCode 通信错误，请在微信中重新发起请求"); 
    return new ModelAndView((View)new RedirectView(url + "&code=" + code));
  }
  
  @RequestMapping({"/open/oauth"})
  public ResultUtil openOauth(HttpServletRequest request) {
    ResultUtil result = getResult();
    try {
      String code = request.getParameter("code");
      Integer tenantId = getTenantId(request);
      if (tenantId == null || StringUtils.isBlank(code)) {
        System.out.println("通信错误，请在微信中重新发起请求");
        return null;
      } 
      TWeixinConfig config = this.tWeixinConfigService.findByTenantId(tenantId);
      PlatformAccount account = new PlatformAccount(config);
      JSONObject jo = account.getOauthInfo(code);
      String openid = jo.getStr("openid");
      System.out.println(openid);
      if (StringUtils.isBlank(openid)) {
        result.setCode(ResultUtil.ERROR_CODE);
        result.setError(jo.getStr("errmsg"));
        this.logger.error("ApiWxController openOauth error!", jo.getStr("errmsg"));
      } 
      TWeixinUser user = this.tWeixinUserService.getByOpenId(openid);
      if (user == null) {
        jo = Account.getOauthUserInfo(jo.getStr("access_token"), openid);
        user = (TWeixinUser)jo.toBean(TWeixinUser.class);
        user.setUniacid(tenantId);
        this.tWeixinUserService.save(user);
      } 
      result.putParams("openid", openid);
      result.putParams("user", user);
    } catch (Exception e) {
      result.setCode(ResultUtil.ERROR_CODE);
      result.setError(e.getMessage());
      this.logger.error("ApiWxController openOauth error!", e);
    } 
    return result;
  }
  
  @RequestMapping({"/getAppId"})
  public ResultUtil getAppId(HttpServletRequest request) {
    ResultUtil result = getResult();
    try {
      Integer tenantId = getTenantId(request);
      TWeixinConfig config = this.tWeixinConfigService.findByTenantId(tenantId);
      if (config == null || StringUtils.isBlank(config.getAppid()))
        throw new Exception("APPID获取异常"); 
      result.putParams("appid", config.getAppid());
    } catch (Exception e) {
      result.setCode(ResultUtil.ERROR_CODE);
      result.setError(e.getMessage());
      this.logger.error("ApiWxController getAppId error!", e);
    } 
    return result;
  }
}
